本篇同步發布於Blog:[解題] LeetCode - 66 Plus One
LeetCode
66 - Plus One
https://leetcode.com/problems/plus-one/
輸入1個陣列digits,每個元素代表1個整數的位數,求第1位數加1後的digits的變化,包含能進位。
比如範例輸入的digits = [1,2,3],代表整數123,加1後變成124,而要回傳[1,2,4]。
如果digits = [9],代表整數9,加1後變成10,而要回傳[1, 0]。
從最小位數開始加1後,檢查是否有進位,有進位則往更高位數加1。特殊狀況是遇到最高位數是9且又加1,需另外開空間存。
難度為Easy
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int curAddDigit = 1;
int nextAddDigit = 0;
vector<int> ans(digits.size());
for(int i = digits.size() - 1;i >= 0;--i){
ans[i] = digits[i];
}
for(int i = digits.size() - 1;i >= 0;--i){
nextAddDigit = (curAddDigit + ans[i]) / 10;
ans[i] = (curAddDigit + ans[i]) % 10;
curAddDigit = nextAddDigit;
if(curAddDigit == 0){
break;
}
}
if(nextAddDigit == 1){
ans.insert(ans.begin(), 1);
}
return ans;
}
};
int main() {
Solution sol;
vector<int> digits{1,2,3};
vector<int> ans = sol.plusOne(digits);
for(int num : ans){
cout << num << " ";
}
return 0;
}
using System;
using System.Collections.Generic;
namespace LeetCode66
{
public class Solution {
public int[] PlusOne(int[] digits) {
int curAddDigit = 1;
int nextAddDigit = 0;
List<int> ans = new List<int>(digits);
for(int i = digits.Length - 1;i >= 0;--i){
nextAddDigit = (curAddDigit + ans[i]) / 10;
ans[i] = (curAddDigit + ans[i]) % 10;
curAddDigit = nextAddDigit;
if(curAddDigit == 0){
break;
}
}
if(nextAddDigit == 1){
ans.Insert(0, 1);
}
return ans.ToArray();
}
}
public class Program
{
public static void Main()
{
Solution sol = new Solution();
int[] digits = new int[]{1,2,3};
int[] ans = sol.PlusOne(digits);
foreach(int num in ans){
Console.Write(" " + num);
}
Console.Read();
}
}
}
https://github.com/u8989332/ProblemSolving/blob/master/LeetCode/C%2B%2B/1-99/66.cpp
https://github.com/u8989332/ProblemSolving/blob/master/LeetCode/C%23/1-99/66.cs